package com.chaosj.memory.command;

import com.chaosj.memory.CmdParserHandler;
import com.google.common.base.Joiner;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @className: AbstractCommand
 * @description:
 * @author: caoyangjie
 * @date: 2022/3/21
 **/
public abstract class AbstractCommand {
    final static Cache<String, String> cache = CacheBuilder.newBuilder()
            //设置cache的初始大小为10，要合理设置该值
            .initialCapacity(10)
            //设置并发数为5，即同一时间最多只能有5个线程往cache执行写入操作
            .concurrencyLevel(5)
            .maximumSize(2000)
            //设置cache中的数据在写入之后的存活时间为10秒
            .expireAfterWrite(30, TimeUnit.MINUTES)
            //构建cache实例
            .build();

    protected String defaultInvoke(String[] args) {
        try {
            return cache.get(Joiner.on(" ").join(args), ()->{
                StringBuffer stringBuffer = new StringBuffer();
                new CmdParserHandler().execute(args, stringBuffer);
                return stringBuffer.toString().replaceAll("\t","    ");
            });
        } catch (ExecutionException e) {
        }
        return "指令执行结果将被缓存,当前结果执行超时!您可以选择再次执行.将获取最近一次执行结果!";
    }
}
